package com.wangyg.juc.ProducerConsumer.version3;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by wangyg6 on 2018/7/11.
 *
 */
public class Producer implements Runnable {
	private List<String> queue;
	private static final AtomicInteger integer = new AtomicInteger();

	public Producer setQueue(List<String> queue) {
		this.queue = queue;
		return this;
	}

	@Override
	public void run() {
		while (true) {
			Main.lock.lock();
			if (queue.size() >= 5) {
				try {
					Main.empty.signalAll();
					Main.full.await();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			if (queue.size() < 5) {//需要防止不同线程干扰，导致的容量超出，以及容量小于0.而且必须在锁中，不加锁无法实现
				int i = integer.incrementAndGet();
				queue.add(String.valueOf(i));
				System.out.println(Thread.currentThread().getName() + "生产了" + i + "______" + queue.size());
			}
			Main.lock.unlock();
			try {
				Thread.sleep(10);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

		}
	}
}
